import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:lz_login/src/serve/kd_login_api.dart';
import 'package:lz_ui/kd_ui.dart';
import 'package:get/get.dart';
import 'package:lz_app_core/extension/kd_extension.dart';

class KDVerificationCodeWidget extends StatefulWidget {
  /// 输入的电话
  final String Function() phoneCall;

  /// 输入
  final Function(String) inputCode;

  /// 是否已经点击
  final Function(bool)? hasGetCode;

  /// 0登录 1注册 2忘记密码 3修改手机-老手机验证码 4修改手机-新手机验证码
  final int type;

  KDVerificationCodeWidget(
      {super.key,
      required this.phoneCall,
      this.hasGetCode,
      required this.inputCode,
      this.type = 1});

  @override
  State<KDVerificationCodeWidget> createState() =>
      _KDVerificationCodeWidgetState();
}

class _KDVerificationCodeWidgetState extends State<KDVerificationCodeWidget> {
  var isTimeRun = false;
  Timer? timer;
  var codeString = "获取验证码".obs;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if (timer != null) {
      timer!.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text("* ",
                style: TextStyle(color: KDColor.errRed, fontSize: KD.font(32))),
            // 验证码
            Text(
              "验证码",
              style: TextStyle(color: KDColor.title, fontSize: KD.font(32)),
            ),
          ],
        ),

        // space
        SizedBox(height: KD.size(16)),

        // input
        KDFormInputWidget(
          child: Row(
            children: [
              Expanded(
                  child: KDTextFiled.aLineInput(
                      onChanged: (p0) => widget.inputCode(p0),
                      maxLength: 4,
                      keyboardType: TextInputType.number)),
              GestureDetector(
                  onTap: _getCode,
                  child: Obx(() => SizedBox(
                        width: KD.size(isTimeRun ? 240 : 180),
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            codeString.value,
                            style: TextStyle(
                                fontSize: KD.font(32), color: KDColor.main),
                          ),
                        ),
                      ))),
            ],
          ),
        ),
      ],
    );
  }

  _getCode() async {
    var phone = widget.phoneCall();

    /// 如果不是有效的电话无法点击
    if (!phone.isPhone) {
      DialogUtils.showToast('手机号码输入有误');
      return;
    }
    if (isTimeRun) {
      return;
    }

    bool isSuccess = false;
    if (widget.type == 0) {
      isSuccess = await KDLoginApi.sendLoginMsgCode(phone);
    } else if (widget.type == 1) {
      isSuccess = await KDLoginApi.sendRegisterMsgCode(phone);
    } else if (widget.type == 2) {
      isSuccess = await KDLoginApi.sendForgotPwdVerification(phone);
    } else if (widget.type == 3) {
      isSuccess = await KDLoginApi.appUpdatePhoneByAppSendSms(phone: phone);
    } else if (widget.type == 4) {
      isSuccess = await KDLoginApi.appUpdateNewPhoneSendSms(phone: phone);
    }

    if (!isSuccess) {
      return;
    }

    if (widget.hasGetCode != null) {
      widget.hasGetCode!(true);
    }
    isTimeRun = true;
    int count = 60;
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      count--;
      codeString.value = "重新获取($count)";
      if (count <= 0) {
        codeString.value = "获取验证码";
        isTimeRun = false;
        timer.cancel();
      }
    });
  }
}
